<?php

namespace App\Http\Controllers;

use App\Http\Requests\AuthRequests\SmsCodeRequest;
use App\Services\Sms;
use App\Models\User;
use GuzzleHttp\Client;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Overtrue\EasySms\PhoneNumber;

class SmsController extends Controller
{
    /**
     * @param SmsCodeRequest $request
     * @param Sms            $smsService
     *
     * @return Response
     */
    public function sendCode(SmsCodeRequest $request, Sms $smsService)
    {
        $mobile = $request->input('mobile');
        if ($mobile) {
            $area = $request->input('area') ?? User::where('mobile', $request->input('mobile'))->value('area');
            if (!$area) {
                $this->error(70000);
            }
            $phoneNumber = new PhoneNumber($mobile, $area);
        } else {
            if (Auth::check()) {
                $phoneNumber = new PhoneNumber(Auth::user()->mobile, Auth::user()->area);
                $mobile = Auth::user()->mobile;
            } else {
                $this->error(40001);
            }
        }

        $ip = $request->ip();

        $smsService->checkThrottle($ip, $phoneNumber);

        if (app()->isLocal()) {
            Cache::put('sms_code:' . $phoneNumber->getUniversalNumber(), 123456, now()->addMinutes(15));
        } else {
            $code = rand(111111, 999999); // 验证码
            $http = new Client;
            try {
                Cache::put('sms_code:' . $phoneNumber->getUniversalNumber(), $code, now()->addMinutes(15));
//                $response = $http->post('https://sms.yunpian.com/v2/sms/single_send.json', [
//                    'form_params' => [
//                        'apikey' => '49993b9246abf0c11023a9699dabe546',
//                        'mobile' => $mobile,
//                        'text' => '【轩谷科技】您的验证码是：' . $code . '，请在15分钟內填写，如非本人操作，请忽略此条资讯',
//                    ],
//                    'verify' => false,
//                ]);
//                $content = '您的验证码是'.$code.'。如非本人操作，请忽略本短信';
                $content = '【轩谷】 您的验证码是'. $code .'。如非本人操作，请忽略本短信';
                $response = $http->get("http://m.5c.com.cn/api/send/index.php?username=xuangu_hy&password_md5=62c8ad0a15d9d1ca38d5dee762a16e01&apikey=49e1292f8441b23bf80ea333a8796187&mobile={$mobile}&encode=UTF-8&content={$content}", ['verify' => false]);
            } catch (\Exception $exception) {
                logger('==============SMS===============');
                Log::info($exception);
                $this->error(70002);
            }

            $content = $response->getBody()->getContents();
            if (!Str::contains($content, 'success')) {
                $this->error(70003);
            }
//            $result = json_decode($content, true);
//            if ($result['code'] != 0) {
//                $this->error(70000);
//            }
            //            $smsService->sendCode($phoneNumber);
        }

        $smsService->setThrottle($ip, $phoneNumber);

        return $this->null();
    }
}
